package com.dididoctor.doctor.Activity.Usercentre.Authentication;

import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.dididoctor.doctor.MV.EduActivity;
import com.dididoctor.doctor.R;
import com.dididoctor.doctor.Utils.Util;

/**
 * Created by boy on 2016/4/19.
 */
public class BaiDuMapActivity extends EduActivity {
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    private Marker marker;
    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();
    public boolean isFirstIn = true;
    public EditText mTvLocationname;
    public LinearLayout mLlSearch;
    public double Alllatitude, Alllongitude;
    public String AllAddressName;
    private final static int EDITOR_CITY = 010;
    private String AllcityId = "", AllcityName = "";
    private final static int BAIDU_LOCATION_CITY = 010;

    private TextView mTvTitle;
    private ImageView mBtnBack;
    private TextView mTvFinish;
    private MyLocationConfiguration.LocationMode mCurrentMode;

    @Override
    public void setContentLayout() {
        //在使用SDK各组件之前初始化context信息，传入ApplicationContext
        //注意该方法要再setContentView方法之前实现
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_baidumap);
    }


    @Override
    public void init() {

        /**头部**/
        initTitleView();

        mTvLocationname = (EditText) findViewById(R.id.tv_locationname);
        mLlSearch = (LinearLayout) findViewById(R.id.ll_search);
        mLlSearch.setOnClickListener(this);
        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        //设置百度地图初始化比例
        MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.setMapStatus(mapStatusUpdate);
        //普通地图
        mBaiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);

        mylocation();


    }

    private void initTitleView() {
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvTitle.setText("医院地址");
        mBtnBack = (ImageView) findViewById(R.id.btn_back);
        mTvFinish = (TextView) findViewById(R.id.tv_finish);
        mTvFinish.setVisibility(View.VISIBLE);
        mTvFinish.setText("保存");
        mTvFinish.setOnClickListener(this);
    }

    /**
     * 定位信息
     */
    private void mylocation() {
        initLocation();
    }

    private void initLocation() {
        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span = 1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {

//            MyLocationData locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())
//                            // 此处设置开发者获取到的方向信息，顺时针0-360
//                    .direction(100).latitude(location.getLatitude())
//                    .longitude(location.getLongitude()).build();
//            mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
//            BitmapDescriptor mCurrentMarker = BitmapDescriptorFactory
//                    .fromResource(R.drawable.icon_marka);
//            MyLocationConfiguration config = new MyLocationConfiguration(mCurrentMode, true, mCurrentMarker);
//            mBaiduMap.setMyLocationConfigeration(config);
//            mBaiduMap.setMyLocationData(locData);

            if (isFirstIn) {
                //纬度
                Alllatitude = location.getLatitude();
                //经度
                Alllongitude = location.getLongitude();

                AllcityId = location.getCityCode();

                AllcityName = location.getCity();

                AllAddressName = location.getAddrStr();

                LatLng point = new LatLng(Alllatitude, Alllongitude);

                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(point).zoom(18.0f);
                //到达定位的中心点
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                isFirstIn = false;
                mTvLocationname.setText(location.getAddrStr());
                addpoint(Alllatitude, Alllongitude);
            }
        }
    }

    /**
     * 添加标注
     *
     * @param latitude
     * @param longitude
     */
    private void addpoint(double latitude, double longitude) {
        //定义Maker坐标点
        LatLng point = new LatLng(latitude, longitude);


        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.drawable.icon_marka);

        OverlayOptions options = new MarkerOptions()
                .position(point)  //设置marker的位置
                .icon(bitmap)  //设置marker图标
                .zIndex(1)  //设置marker所在层级
                .draggable(true);  //设置手势拖拽
        //将marker添加到地图上
        marker = (Marker) (mBaiduMap.addOverlay(options));
        marker.setToTop();
        //调用BaiduMap对象的setOnMarkerDragListener方法设置marker拖拽的监听
        mBaiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {

            public void onMarkerDrag(Marker marker) {
                //拖拽中
            }

            public void onMarkerDragEnd(Marker marker) {
                //实例化一个地理编码查询对象
                GeoCoder geoCoder = GeoCoder.newInstance();
                //设置反地理编码位置坐标
                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
                //定义Maker坐标点

                LatLng point = new LatLng(marker.getPosition().latitude, marker.getPosition().longitude);
                op.location(point);
                //发起反地理编码请求(经纬度->地址信息)
                geoCoder.reverseGeoCode(op);
                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                        //获取点击的坐标地址
                        mTvLocationname.setText(arg0.getAddress());
                        AllAddressName = arg0.getAddress();
                        Alllatitude = arg0.getLocation().latitude;
                        Alllongitude = arg0.getLocation().longitude;
                        ReverseGeoCodeResult.AddressComponent addressDetail = arg0.getAddressDetail();
                        AllcityName = addressDetail.city;
//                        if (arg0.getPoiList() != null && arg0.getPoiList().size() > 0) {
////                            AllcityId = arg0.getPoiList().get(0).city;
//                            AllcityName = arg0.getPoiList().get(0).city;
//                        }

                    }

                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
                    }
                });
                //拖拽结束
            }

            public void onMarkerDragStart(Marker marker) {
                //开始拖拽
            }
        });

    }

    @Override
    public void onClickEvent(View view) {
        switch (view.getId()) {
            case R.id.ll_search:
                Intent intent = new Intent(this, SelectAddressActivity.class);
                intent.putExtra("cityName", AllcityName);
                intent.putExtra("cityId", AllcityId);
                startActivityForResult(intent, EDITOR_CITY);
                break;
            case R.id.tv_finish:
                String trim = mTvLocationname.getText().toString().trim();
                if (!"".equals(trim) && trim !=null){
                    BaiDuMapDialog BDM = new BaiDuMapDialog(BaiDuMapActivity.this, mTvLocationname.getText().toString().trim(), new BaiDuMapDialog.Submitlistener() {
                        @Override
                        public void submitok() {
                            Intent finishintent = new Intent(BaiDuMapActivity.this, AuthenticationActivity.class);
                            finishintent.putExtra("addressStr", mTvLocationname.getText().toString().trim());
                            finishintent.putExtra("latitude", Alllatitude);
                            finishintent.putExtra("longitude", Alllongitude);
                            finishintent.putExtra("cityName", AllcityName);
                            finishintent.putExtra("cityId", AllcityId);
                            setResult(Activity.RESULT_OK, finishintent);
                            finish();
                        }
                    });
                    BDM.show();
                }else{
                    showToastMessage("请填写您的执业医院");
                }

                break;
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();
    }

    @Override
    protected void onDestroy() {

        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        mMapView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case BAIDU_LOCATION_CITY:
                    AllAddressName = data.getStringExtra("addressStr");
                    Alllatitude = data.getDoubleExtra("latitude", 0);
                    Alllongitude = data.getDoubleExtra("longitude", 0);
                    AllcityName = data.getStringExtra("cityname");
                    AllcityId = data.getStringExtra("cityId");
                    MapStatus.Builder builder = new MapStatus.Builder();

                    //定义Maker坐标点
                    LatLng point = new LatLng(Alllatitude, Alllongitude);
                    builder.target(point).zoom(18.0f);

                    //到达定位的中心点
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));

                    //获取点击的坐标地址
                    mTvLocationname.setText(AllAddressName);

                    marker.setPosition(point);

                    break;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
